
import asyncio
import json
import time
from loguru import logger
import websockets
from service import GetUserByToken

wsPort = 8766
# 存放用户的连接
clientMap = {}
# 存放匹配的用户
clientMatch = []
# 存放token和id对应
clientTokenId = {}
# 存放两个游戏玩家的对应
clientStart = {}
# 存放用户信息
allUserById = {}


async def JsonPatch(data):
    global clientMatch
    token = data['token']
    if data['cmd'] == 0:
        # 心跳
        userId = clientTokenId[token]
        clientMap[userId]['heart'] = 2
    elif data['cmd'] == 1:
        userId = clientTokenId[token]
        if len(clientMatch) == 1 and clientMatch[0] == token:
            return
        # 添加用户到匹配队列
        clientMatch.append(token)
        if len(clientMatch) >= 2:
            # 匹配成功,开始游戏
            id1 = clientTokenId[clientMatch[0]]
            id2 = clientTokenId[clientMatch[1]]
            if id1 == id2:
                clientMatch = clientMatch[1:2]
                return
            str1 = '{"cmd": 1, "dstId": ' + str(id2) + ', "isRed": true}'
            str2 = '{"cmd": 1, "dstId": ' + str(id1) + ', "isRed": false}'
            clientStart[id1] = id2
            clientStart[id2] = id1
            await clientMap[id1]['conn'].send(str1)
            await clientMap[id2]['conn'].send(str2)
            clientMatch = []
    elif data['cmd'] == 2:
        # 收到点击消息
        id1 = clientTokenId[token]
        id2 = clientStart[id1]
        str1 = '{"cmd": 2, "dstId": ' + str(id2) + ', "row": ' + str(data['click']['row']) + ', "col":' + str(
            data['click']['col']) + ', "id": ' + str(data['click']['id']) + '}'
        await clientMap[id2]['conn'].send(str1)
    elif data['cmd'] == 10:
        # 收到普通聊天消息
        id1 = clientTokenId[token]
        id2 = clientStart[id1]
        user1 = allUserById[id1]
        str1 = '{"cmd": 10, "dstUsername": "' + user1['user_name'] + '", "content": "' + data['content'] + '"}'
        await clientMap[id2]['conn'].send(str1)
    elif data['cmd'] == 20:
        # 收到悔棋消息
        id1 = clientTokenId[token]
        id2 = clientStart[id1]
        user1 = allUserById[id1]
        name = user1['user_name']
        if data['content'] == '请求悔棋':
            str1 = '{"cmd": 20, "dstUsername": "' + name + '", "content": "请求悔棋"}'
            await clientMap[id2]['conn'].send(str1)
        elif data['content'] == '拒绝悔棋':
            str1 = '{"cmd": 20, "dstUsername": "' + name + '", "content": "拒绝悔棋"}'
            await clientMap[id2]['conn'].send(str1)
        elif data['content'] == '同意悔棋':
            str1 = '{"cmd": 20, "dstUsername": "' + name + '", "content": "同意悔棋"}'
            await clientMap[id1]['conn'].send(str1)
            await clientMap[id2]['conn'].send(str1)


async def MainHeart():
    while True:
        for x in clientMap:
            print(x)
            await clientMap[x]['conn'].send('{"cmd":0}')
        await asyncio.sleep(5)


# async def Heart(websocket):
#     while True:
#         await websocket.send('{"cmd":0}')
#         await asyncio.sleep(5)

async def echo(websocket, path):
    # fetch msg
    token = path[path.find("token") + 6:]
    print(token)
    user = GetUserByToken(token)
    if user == -1:
        return
    userId = user['id']
    if userId < 0:
        return
    clientMap[userId] = {}
    clientMap[userId]['conn'] = websocket
    clientMap[userId]['heart'] = 0
    clientTokenId[token] = userId
    allUserById[userId] = user

    await websocket.send('{"success":true,"cmd":0}')
    async for message in websocket:
        print("got a message:{}".format(message))
        # 解析数据
        try:
            data = json.loads(message)
            await JsonPatch(data)
        except Exception as e:
            raise e
            logger.info(e)
        await websocket.send(message)


async def main():
    # start a websocket server
    async with websockets.serve(echo, "localhost", wsPort):
        await asyncio.Future()  # run forever


def runHart():
    asyncio.run(MainHeart())


def runWS():
    asyncio.run(main())
